/*************************************************************************
 * This file is part of HeroesForge.
 *
 * HeroesForge is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * HeroesForge is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with HeroesForge.  If not, see <http://www.gnu.org/licenses/>.
 *************************************************************************/
package org.diskordia.heroesforge.core.security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.diskordia.heroesforge.core.util.Converter;

/**
 * Salted hash calculator.
 * 
 * @author lehmamic
 */
public class SaltedHash {
	private static final String SALT = "SALT4HEROESFORGE";
	private static final String ALGORITHM = "SHA";
	
	private String customSalt;
	
	/**
	 * Initializes an instance of the @see SaltedHash class.
	 */
	public SaltedHash(){
		this(SALT);
	}
	
	/**
	 * Initializes an instance of the @see SaltedHash class.
	 *
	 * @param salt the string will be added to the data for salting the hash.
	 */
	public SaltedHash(String salt){
		if(salt == null){
			throw new IllegalArgumentException("The salt string is a null reference.");
		}
		
		this.customSalt = salt;
	}
	
	/**
	 * Generates a salted hash code for the provided data.
	 * 
	 * @param data the data for building the hash of.
	 * @return the calculated salted hash code.
	 */
	public String GenerateHash(String data){
		if(data == null){
			throw new IllegalArgumentException("The data string is a null reference.");
		}
		
		String hash;
		try {
			MessageDigest digest = MessageDigest.getInstance(ALGORITHM);
			
			digest.update(this.saltData(data));
			hash =  Converter.BytesToHex(digest.digest());
		} catch (NoSuchAlgorithmException e) {
			hash = "";
		}

		return hash;
	}
	
	private byte[] saltData(String data){
		StringBuilder builder = new StringBuilder();
		builder.append(data);
		builder.append(";");
		builder.append(this.customSalt);
		
		byte[] result;
		try {
			result = builder.toString().getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			result = new byte[0];
		}

		return result;
	}
}
